import * as server from "@minecraft/server";
import * as data_prompt from "../data/prompt";
import * as data_entity from "../data/entity";
import * as data_story from "../data/story";
import * as power_property from "./power_property";
import * as native_tools from "./native_tools";
import * as achieve_plan from "./achieve_plan";
import * as math_tools from "./math_tools";
export { UnloadInventoryAndPackage, UnloadInventoryAndDestroy, CompleteSummonAnimation, ParticleSummonAnimation, DisplayChunkBoundary, AnalysisWeight, GetTargetIntel, NumberParticleDisplay, FloatingTextDisplay, AlterMessageNotify, ErrorMessage, PlayPrompt, IsEnable, IsErupt, };
function IsErupt(object) {
    const getData = power_property.GetProperty(object);
    const eruptOdds = getData.erupt_odds + getData.raise_erupt_odds;
    return IsEnable(eruptOdds);
}
;
function IsEnable(input) {
    return math_tools.Random({ min: 0, max: 100 }) <= input;
}
;
function AnalysisWeight(input) {
    const proto = [...input];
    const scale = proto.reduce((acc, cur) => acc + cur[1], -1);
    const source = [];
    const index = math_tools.Random({ min: 0, max: scale }, true);
    proto.forEach(info => { for (let index = 0; index < info[1]; index++)
        source.push(info[0]); });
    return { source, index, output: source[index] };
}
;
function NumberParticleDisplay(source, input, offset) {
    if (input > 99999)
        return;
    const molang = new server.MolangVariableMap();
    const RGB = [...data_story.rune_color.values()];
    const intel = input.toString().split('').reverse().map(value => parseInt(value, 10));
    const index = math_tools.Random({ min: 0, max: RGB.length - 1 }, true);
    molang.setVector3('variable.offset', math_tools.Vector.add(offset, { x: Math.random() - 0.5, y: Math.random() - 0.5, z: Math.random() - 0.5 }));
    molang.setColorRGB('variable.color', RGB[index]);
    intel.forEach((value, index) => {
        molang.setVector3('variable.property', { x: value, y: index, z: intel.length });
        native_tools.TrySpawnParticle(source.dimension, 'scripts:setting.number_display', source.location, molang);
    });
}
;
function CompleteSummonAnimation(player, location) {
    const camera = player.camera;
    ParticleSummonAnimation(player, location);
    camera.setCamera('minecraft:free', { location: math_tools.Vector.add(location, { x: 15, y: 35, z: 15 }), facingLocation: location, easeOptions: { easeTime: 2 } });
    server.system.runTimeout(() => camera.setCamera('minecraft:free', { location: math_tools.Vector.add(location, { x: -15, y: 5, z: 15 }), facingLocation: location, easeOptions: { easeTime: 2 } }), 80);
    server.system.runTimeout(() => camera.fade({ fadeColor: { red: 0, green: 0, blue: 0 }, fadeTime: { fadeInTime: 1, fadeOutTime: 0.5, holdTime: 0.5 } }), 120);
    server.system.runTimeout(() => camera.setCamera('minecraft:free', { location, facingLocation: location, easeOptions: { easeTime: 1 } }), 120);
    server.system.runTimeout(() => camera.clear(), 140);
}
;
function ParticleSummonAnimation(player, location) {
    const molang = new server.MolangVariableMap();
    molang.setFloat('variable.size', 10);
    molang.setFloat('variable.direction', 3);
    player.spawnParticle('scripts:path_round', location, molang);
    player.spawnParticle('scripts:path_diamond', location, molang);
    player.spawnParticle('scripts:path_butterfly', location, molang);
    molang.setFloat('variable.size', 13);
    player.spawnParticle('scripts:path_round', location, molang);
    server.system.runTimeout(() => {
        molang.setFloat('variable.type', 0);
        molang.setVector3('variable.direction', math_tools.Vector.CONSTANT_UP);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: 5, y: 0, z: 0 }), molang);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: -5, y: 0, z: 0 }), molang);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: 0, y: 0, z: 5 }), molang);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: 0, y: 0, z: -5 }), molang);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: 3.725, y: 0, z: 3.725 }), molang);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: -3.725, y: 0, z: -3.725 }), molang);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: -3.725, y: 0, z: 3.725 }), molang);
        player.spawnParticle('scripts:path_ray', math_tools.Vector.add(location, { x: 3.725, y: 0, z: -3.725 }), molang);
        player.playSound('conduit.attack', { volume: 10, location: math_tools.Vector.add(location, { x: 15, y: 35, z: 15 }) });
    }, 40);
}
;
function GetTargetIntel(object) {
    const entity = object.getEntitiesFromViewDirection()[0]?.entity;
    const block = object.getBlockFromViewDirection()?.block;
    const message = [];
    if (entity && entity.isValid()) {
        if (entity.typeId != 'minecraft:item')
            return GetEntityIntel(entity, message);
        const item = entity.getComponent('minecraft:item')?.itemStack;
        if (!item)
            return [{ text: '§4 未知物品 §r' }];
        return GetItemStackIntel(item, message);
    }
    else if (block && block.isValid())
        return GetBlockIntel(block, message);
    return [{ text: '§4 未知目标 §r' }];
}
;
function GetTargetTags(object) {
    return object.getTags().map(info => { return { text: info + '\n' }; });
}
;
function GetBlockRecord(states) {
    let [output, name, value] = [[], [], []];
    for (let index in states) {
        value.push(states[index]);
        name.push(index);
    }
    ;
    for (let α = 0; α < name.length; α++) {
        output.push({ text: `§r§l<§r§5 ${name[α]} §7:§2 ${value[α]} §r§l>§r\n` });
    }
    ;
    return output;
}
;
function GetInventoryIntel(container, message) {
    if (container)
        for (let index = 0; index < container.size; index++) {
            const item = container.getItem(index);
            if (!item)
                continue;
            message.push(native_tools.ItemTranslate(item), { text: `§r : §2${item.amount}§r\n` });
        }
    ;
}
;
function GetItemStackIntel(item, message) {
    const durability = item.getComponent('minecraft:durability');
    const info = [
        { text: '§5§o§l[§9 物品 §5]§r : ' },
        native_tools.ItemTranslate(item),
        { text: ' → ' },
        { text: item.typeId },
        { text: `\n\n§5§o§l[§9 数量 §5]§r : ${item.amount}` },
        { text: `\n\n§5§o§l[§9 耐久 §5]§r : ${durability?.damage ?? 0}/${durability?.maxDurability ?? 0}` },
        { text: '\n\n§5§o§l[§9 标签 §5]§r :\n' }
    ];
    message.push(...info, ...GetTargetTags(item));
    return message;
}
;
function GetEntityIntel(entity, message) {
    const getHealth = entity.getComponent('minecraft:health');
    const getBasisSpeed = entity.getComponent('minecraft:movement');
    const getisTether = entity.getComponent('minecraft:leashable');
    const getTameable = entity.getComponent('minecraft:tameable');
    const getMagmaSpeed = entity.getComponent('minecraft:lava_movement');
    const getWaterSpeed = entity.getComponent('minecraft:underwater_movement');
    const getAllComponentsID = entity.getComponents().map(info => [{ text: info.typeId + '\n' }][0]);
    const getTameItems = getTameable ? getTameable.getTameItems.map(info => { return { rawtext: [{ text: '\n' }, native_tools.ItemTranslate(info)] }; }) : [{ text: '\n' }];
    const info = [
        { text: '§5§o§l[§9 实体 §5]§r : ' },
        native_tools.EntityTranslate(entity),
        { text: ' → ' },
        { text: entity.typeId },
        { text: `\n\n§5§o§l[§9 位置 §5]§r : §n${math_tools.Vector.toString(entity.location)}§r` },
        { text: `\n\n§5§o§l[§9 血量 §5]§r : §2${getHealth?.currentValue ?? 0}/${getHealth?.defaultValue ?? 0}§r` },
        { text: `\n\n§5§o§l[§9 能否栓绳 §5]§r : §6${!!getisTether}§r` },
        { text: `\n\n§5§o§l[§9 陆地移速 §5]§r : §2${Math.floor((getBasisSpeed?.defaultValue ?? 0) * 100) / 100}§r` },
        { text: `\n\n§5§o§l[§9 水下移速 §5]§r : §2${Math.floor((getWaterSpeed?.defaultValue ?? 0) * 100) / 100}§r` },
        { text: `\n\n§5§o§l[§9 熔岩移速 §5]§r : §2${Math.floor((getMagmaSpeed?.defaultValue ?? 0) * 100) / 100}§r` },
        { text: '\n\n§5§o§l[§9 驯服材料 §5]§r : §6' },
    ];
    const container = entity.getComponent('inventory')?.container;
    const inventory = [{ text: '§5§o§l[§9 背包 §5]§r :\n' }];
    GetInventoryIntel(container, inventory);
    message.push(...info, ...getTameItems, { text: '\n§5§o§l[§9 标签 §5]§r :\n' }, ...GetTargetTags(entity), { text: '\n§5§o§l[§9 组件 §5]§r:\n' }, ...getAllComponentsID, ...inventory);
    return message;
}
;
function GetBlockIntel(block, message) {
    const states = block.permutation.getAllStates();
    const info = [
        { text: '§5§o§l[§9 方块 §5]§r : ' },
        native_tools.BlockTranslate(block),
        { text: ' → ' },
        { text: block.typeId },
        { text: `\n\n§5§o§l[§9 红石能量 §5]§r : §4${block.getRedstonePower() ?? 0}§r` },
        { text: '\n\n§5§o§l[§9 方块状态 §5]§r :\n' },
    ];
    const container = block.getComponent('inventory')?.container;
    const inventory = [{ text: '\n§5§o§l[§9 方块容器 §5]§r :\n' }];
    GetInventoryIntel(container, inventory);
    message.push(...info, ...GetBlockRecord(states), { text: '\n§5§o§l[§9 方块标签 §5]§r :\n' }, ...GetTargetTags(block), ...inventory);
    return message;
}
;
function PlayPrompt(object, type) {
    const intel = data_prompt.entry.get(type);
    const message = { text: '「 星之引导 」: ' };
    if (object.hasTag('prompt:' + type) || !intel)
        return;
    intel.forEach(info => server.system.runTimeout(() => object.sendMessage([message, info.refer]), info.delay));
    intel.forEach(info => server.system.runTimeout(() => object.playSound('resonate.amethyst_block'), info.delay));
    object.addTag('prompt:' + type);
}
;
function UnloadInventoryAndPackage(target, player, material, itemName, itemLore) {
    if (target instanceof server.Player)
        return;
    const container = target.getComponent('inventory')?.container;
    const items = [];
    const types = target.getDynamicPropertyIds();
    const tags = target.getTags();
    const anchor = math_tools.Vector.copy(target.location);
    const nameTag = target.nameTag.length >= 1 ? target.nameTag : data_entity.name_mapping.get(target.typeId);
    types.sort((a, b) => a[0].toLowerCase().charCodeAt(0) - b[0].toLowerCase().charCodeAt(0));
    if (container)
        for (let index = 0; index < container.size; index++) {
            const item = container.getItem(index);
            if (!item)
                continue;
            items.push(item);
            container.setItem(index);
        }
    ;
    types.forEach(type => material.setDynamicProperty(type, target.getDynamicProperty(type)));
    material.setDynamicProperty('reduction_pureness:tags', JSON.stringify(tags));
    material.setDynamicProperty('reduction_pureness:name', target.nameTag);
    material.setDynamicProperty('reduction_pureness:type', target.typeId);
    material.nameTag = itemName + nameTag + '§r';
    material.setLore(itemLore);
    server.system.runTimeout(() => { native_tools.TrySpawnItem(player.dimension, material, player.getHeadLocation()); }, 10);
    server.system.runTimeout(() => { items.forEach(item => native_tools.TrySpawnItem(player.dimension, item, anchor)); }, 10);
    target.remove();
}
;
function UnloadInventoryAndDestroy(target) {
    const container = target.getComponent('inventory')?.container;
    const items = [];
    const location = math_tools.Vector.copy(target.location);
    const dimension = server.world.getDimension(target.dimension.id);
    if (container)
        for (let index = 0; index < container.size; index++) {
            const item = container.getItem(index);
            if (!item)
                continue;
            items.push(item);
            container.setItem(index);
        }
    ;
    server.system.runTimeout(() => { items.forEach(item => native_tools.TrySpawnItem(dimension, item, location)); }, 10);
    target.remove();
}
;
function AlterMessageNotify(title, block, message) {
    const chunkString = math_tools.Vector.toString(math_tools.Vector.chunkLocation(block.location));
    const entry = data_story.message_notify.get(chunkString) ?? new Map();
    const rawMessage = {
        rawtext: [
            { text: '\n| §l§p' },
            { text: block.dimension.id },
            { text: '§r | §a' },
            { text: math_tools.Vector.toString(block.location) },
            { text: '§r |\n\n' },
            message
        ]
    };
    entry.set(title, rawMessage);
    data_story.message_notify.set(chunkString, entry);
    if (!message.rawtext)
        FloatingTextDisplay(block, message.text ?? '未知');
}
;
function FloatingTextDisplay(block, text) {
    block.dimension.getEntitiesAtBlockLocation(block.location).forEach(entity => { if (entity.typeId == 'entity_sundry:name_display')
        entity.remove(); });
    server.system.run(() => {
        const entity = native_tools.TrySpawnEntity(block.dimension, 'entity_sundry:name_display', block.bottomCenter());
        if (entity instanceof server.Entity)
            entity.nameTag = text ?? '未知';
    });
}
;
function ErrorMessage(title, block, message) {
    const type = 'error -> ' + block.typeId;
    const token = achieve_plan.ControlEventTrigger.BlockToken(type, block, 40);
    if (!token)
        return;
    const molang = new server.MolangVariableMap();
    molang.setFloat('variable.direction', 3);
    molang.setFloat('variable.size', 3);
    native_tools.TrySpawnParticle(block.dimension, 'scripts:path_comet', block.center(), molang);
    AlterMessageNotify(title, block, message);
}
;
function DisplayChunkBoundary(source) {
    const anchor = math_tools.Vector.add(source.location, { x: 0, y: -16, z: 0 });
    const startPlace = math_tools.Vector.chunkLocation(anchor, false);
    const donePlace = math_tools.Vector.add(startPlace, { x: 16, y: 32, z: 16 });
    achieve_plan.PathExecute.CreateForFrame('显示区块边界', {
        particles: ['constant:prompt_route'],
        location_group: [],
        dimension: source.dimension,
        cooldown: 1,
        speed: 1
    }, startPlace, donePlace);
}
;
;
